package com.metrictracker.ws;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.resource.Delete;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ResourceException;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.metrictracker.model.Metric;
import com.metrictracker.model.MetricDao;
import com.metrictracker.model.MetricGoal;
import com.metrictracker.model.MetricGoalDao;
import com.metrictracker.model.MetricValue;
import com.metrictracker.model.MetricValueDao;
import com.metrictracker.util.ExceptionManager;


/**
 * Resource which has only one representation.
 * 
 */
public class ManageMetric extends MetricTrackerServerResource {

	private static final Logger log = Logger.getLogger(ManageMetric.class.getName());
	
	@Get
	public String represent() {
		Metric metric = getMetric();
		StringBuffer sb = new StringBuffer("");
		sb.append("Metric Name: " + metric.getName());
		sb.append(System.getProperty("line.separator"));
		sb.append("Metric Date\t\t\t");
		sb.append("Metric Value\t");
		sb.append("Goal Name\t");
		sb.append("Goal Value\t");
		sb.append("Goal Met?\t");
		sb.append("% to Goal\t");
		sb.append(System.getProperty("line.separator"));
		MetricValueDao valueDao = new MetricValueDao();
		MetricGoalDao goalDao = new MetricGoalDao();
		List<MetricGoal> metricGoals = goalDao.listByProperty("metricKey", metric.getKey());
		Iterator<MetricValue> values =  valueDao.listByProperty("metricKey", metric.getKey()).iterator();
		while (values.hasNext()) {
			MetricValue value = values.next();
			for (int i=0; i< metricGoals.size(); i++) {
				String isGoalMet = "N";
				MetricGoal goal = metricGoals.get(i);
				if (value.getTimeFrame().after(goal.getEffectivityDate()) &&
						value.getTimeFrame().before(goal.getExpirationDate())) {
					if (goal.getGoalType().equals(MetricGoal.HIGHISBETTER) && goal.getGoal() <= value.getValue()) {
						isGoalMet = "Y";
					}
					else if (goal.getGoalType().equals(MetricGoal.LOWISBETTER) && goal.getGoal() >= value.getValue()) {
						isGoalMet = "Y";
					}
				}
				sb.append(value.getTimeFrame());
				sb.append("\t");
				sb.append(value.getValue());
				sb.append("\t\t");
				sb.append(goal.getName());
				sb.append("\t\t");
				sb.append(goal.getGoal());
				sb.append("\t\t");
				sb.append(isGoalMet);
				sb.append("\t\t");
				sb.append(MessageFormat.format("{0,number,#.##%}", value.getValue() / goal.getGoal()));
				sb.append(System.getProperty("line.separator"));
			}
		}
		return sb.toString();
	}

	@Post("form:xml|json")
	public void acceptRepresentation(Representation entity) throws ResourceException { 

		Objectify ofy = ObjectifyService.begin();
		try {
			HashMap<String, String> parameters = getParameters(entity);
			Metric metric = new Metric (parameters.get("metricName"));
			MetricDao metricDao = new MetricDao();
			metricDao.put(metric);
			ofy.put(metric);
			getResponse().setStatus(Status.SUCCESS_CREATED);  
		} catch (UnsupportedEncodingException e) {
			ExceptionManager.logException(log, e);
			getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
			return;
		} catch (IOException e) {
			ExceptionManager.logException(log, e);
			getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
			return;
		}
	}

	@Delete
	public Representation delete() {
		MetricDao dao = new MetricDao();
		Metric metric = getMetric();

		MetricValueDao valueDao = new MetricValueDao();
		List<MetricValue> metricValues = valueDao.listByProperty("metricKey", metric.getKey());
		valueDao.deleteAll(metricValues);

		MetricGoalDao goalDao = new MetricGoalDao();
		List<MetricGoal> metricGoals = goalDao.listByProperty("metricKey", metric.getKey());
		goalDao.deleteAll(metricGoals);

		dao.delete(metric);
		return null;
	}

}

